package com.itany.shop.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 石小俊
 * @date 2023年07月11日 10:16
 */
//@WebFilter(urlPatterns = "/*",initParams = {
//        @WebInitParam(name = "encoding",value = "utf-8"),
//        @WebInitParam(name = "contentType",value = "text/html;charset=utf-8")
//})
public class CharacterEncodingFilter implements Filter {

    private FilterConfig config;

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        String encoding = config.getInitParameter("encoding");
        String contentType = config.getInitParameter("contentType");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding(encoding);
        response.setContentType(contentType);
        chain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
